<?php


namespace App\Console\Commands\Gift;


use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class StatusChange extends Command
{
    //命令名
    protected $signature = 'gift:status-change';

    //命令描述
    protected $description = '修改礼物状态';

    public function __construct()
    {
        parent::__construct();
    }

    //业务处理
    public function handle()
    {
        $giftStatusCrontabs = app('model_gift_status_crontab')
            ->select('id', 'gift_id', 'action')
            ->where('status', 0)->where('set_time', '<=', date('Y-m-d H:i:s'))
            ->get()->toArray();

        foreach ($giftStatusCrontabs as $giftStatusCrontab) {

            DB::beginTransaction();
            try {

                //修改状态为：已处理
                app('model_gift_status_crontab')->where('id', $giftStatusCrontab['id'])->update(['status' => 1]);

                $gift = app('model_gift')->select('sold')->where('id', $giftStatusCrontab['gift_id'])->first();
                if ($gift) {
                    //修改礼物状态
                    $giftStatusCrontab['action'] == 1 ? $sold = 1 : $sold = 2;
                    app('model_gift')->where('id', $giftStatusCrontab['gift_id'])->update(['sold' => $sold]);
                }

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                var_dump($e->getLine() . '|' . $e->getMessage());
            }
        }
    }
}